package com.bdcom.autotest.interaction.socket.bean;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class BasePkg implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	private static Logger log = LoggerFactory.getLogger(BasePkg.class);
	
	
	public final static byte START_FlAG = (byte) 0x9E;
	public final static byte STOP_FLAG = (byte) 0XAE;
	
	
	public BasePkg(  byte cmd, short length, byte[] data ) {
		this.cmd = cmd;
		this.length = length;
		this.data = data;
	}

	public BasePkg(    ) {
		
	}


	public byte start = (byte) 0x9E;
	public byte cmd;
	public short length;
	public byte[] data;
	public byte stop=(byte) 0XAE;
	

	
	
	public byte[] toBytes() {
		byte[] byteArray = null;
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream out = new DataOutputStream(baos); 
		try {
			out.writeByte(start);
			out.writeByte( cmd);
			out.writeShort(length);
			out.write(data);
			out.writeByte(stop);
			byteArray = baos.toByteArray();
			out.close();
			baos.close();
		} catch ( Exception e ) {
			log.error( "" , e);
		}
		
		return byteArray;
	}
	
	
	
	public static BasePkg fromBytes(  byte[] bytes ) {
		
		ByteArrayInputStream bintput = new ByteArrayInputStream(bytes);
		DataInputStream dintput = new DataInputStream(bintput);
		try {
			byte tmpStart = dintput.readByte();
			byte tmpCMD = dintput.readByte();
			short tmpLen = dintput.readShort();
			byte[] datas = new byte[tmpLen]; 
			int read = dintput.read( datas , 0 , tmpLen );
			byte tmpEnd = dintput.readByte();
			
			BasePkg bean = new BasePkg( tmpCMD,  tmpLen , datas);
			return bean;
		} catch (IOException e) {
			log.error( "" , e);
		}
		
		return null;
	}

	public byte getStart() {
		return start;
	}

	public void setStart(byte start) {
		this.start = start;
	}

	public byte getCmd() {
		return cmd;
	}

	public void setCmd(byte cmd) {
		this.cmd = cmd;
	}

	public short getLength() {
		return length;
	}

	public void setLength(short length) {
		this.length = length;
	}

	public byte[] getData() {
		return data;
	}

	public void setData(byte[] data) {
		this.data = data;
	}

	public byte getStop() {
		return stop;
	}

	public void setStop(byte stop) {
		this.stop = stop;
	}
	public static void main(String[] args) {
		System.out.println(START_FlAG);
	}
	

}
